import { BellOutlined, SoundOutlined } from '@ant-design/icons'
import { Badge, Empty, notification, Pagination, Popover } from 'antd'
import { connect } from 'dva'
import { useEffect, useRef, useState } from 'react'

import MessageJump from '@/components/MessageJump'
import { getBasicFn } from '@/utils/dvaUtil/index'

import BannerNotice from '../BannerNotice'
import './index.less'

const namespace = 'notice'

const { toAction } = getBasicFn({ namespace })

const playAudio = () => {
  const au = document.getElementById('J-zmx-notice')
  const auParent = au.parentNode
  try {
    if (!au) {
      return
    }
    au.muted = false
    const res = au.play()
    if (res !== undefined) {
      res.catch(err => {
        const str = err.toLocaleString()
        if (str.includes('NotAllowedError') || str.includes('Dom E')) {
          auParent.style.cssText += ';display:flex;width: auto;height: auto;'
        }
      })
    }
  } catch (err) {
    const str = err.toLocaleString()
    if (str.includes('NotAllowedError')) {
      auParent.style.cssText += ';display:flex;width: auto;height: auto;'
    }
  }
}

/**
 * @param {{modelState: import('@/models/app/notice').state}} param0
 */
const Notice = ({ modelState }) => {
  const { unReadNoticesData, messagePopVisible, voiceReminder } = modelState

  const [openedNoticeIds, setOpenedNoticeIds] = useState([])
  const voiceLinkNoticeIdsMap = useRef({})

  useEffect(() => {
    notification.destroy()
  }, [])

  const toRefreshNoticeModule = (pageConfig = {}, visible) => {
    toAction({ messagePopVisible: visible })
    toAction('pullUnReadNotices', pageConfig)
  }

  const afterViewMessage = ({ noticeId }) => {
    const tmp = [...openedNoticeIds]
    tmp.push(noticeId)
    setOpenedNoticeIds(tmp)
    toAction({ messagePopVisible: false })
    toAction('setReadStatus', { noticeIds: [noticeId] })
  }

  const bannerNoticeList = (unReadNoticesData.bannerNoticeList || []).filter(
    it => !openedNoticeIds.includes(it.noticeId),
  )

  const popUpNoticeList = (unReadNoticesData.popUpNoticeList || []).filter(it => !openedNoticeIds.includes(it.noticeId))

  if (voiceReminder) {
    const needVoiceReminderGroupList = [
      bannerNoticeList.filter(it => it.voiceReminder === 1),
      popUpNoticeList.filter(it => it.voiceReminder === 1),
    ]
    if (needVoiceReminderGroupList[0].length > 0 || needVoiceReminderGroupList[1].length > 0) {
      const tmp = needVoiceReminderGroupList.flat().map(it => it.noticeId)
      if (tmp.some(it => !voiceLinkNoticeIdsMap.current[it])) {
        playAudio()
        tmp.forEach(it => {
          voiceLinkNoticeIdsMap.current[it] = true
        })
      }
    }
  }

  if (popUpNoticeList && popUpNoticeList.length > 0) {
    const tmp = [...openedNoticeIds]
    popUpNoticeList.forEach(it => {
      const { typeDesc, content, onClickMessage } = MessageJump.getResolvedData(it)
      tmp.push(it.noticeId)
      notification.open({
        key: it.noticeId,
        duration: null,
        message: typeDesc,
        description: content,
        onClick: () => {
          notification.close(it.noticeId)
          onClickMessage(it, afterViewMessage).catch()
        },
      })
    })
    setOpenedNoticeIds(tmp)
  }

  return (
    <>
      {Array.isArray(bannerNoticeList) && bannerNoticeList.length > 0 && (
        <div className='bannerNotice-list'>
          <SoundOutlined type='sound' className='mr10px' />
          <BannerNotice afterViewMessage={afterViewMessage} list={bannerNoticeList} />
        </div>
      )}
      <div className='flex items-center justify-center'>
        <Popover
          open={!!messagePopVisible}
          onOpenChange={visible => toRefreshNoticeModule({ current: !visible ? 1 : undefined }, visible)}
          trigger='click'
          title={
            unReadNoticesData.total > 0 && (
              <div className='flex items-center justify-between'>
                <div>未读消息（{unReadNoticesData.total}）</div>
                <a
                  onClick={() => {
                    toAction('setAllReadStatus')
                  }}
                >
                  全部已读
                </a>
              </div>
            )
          }
          content={
            <div
              style={{
                width: '400px',
                maxHeight: '400px',
                overflowY: 'auto',
                background: '#fff',
              }}
            >
              {unReadNoticesData.total > 0 &&
                unReadNoticesData.redPointNoticeList.map(it => (
                  <MessageJump key={it.noticeId} message={it} afterView={afterViewMessage} />
                ))}
              {unReadNoticesData.total > unReadNoticesData.pageSize && (
                <Pagination
                  onClick={e => e.stopPropagation()}
                  style={{ textAlign: 'right', marginTop: 20 }}
                  size='small'
                  total={unReadNoticesData.total}
                  pageSize={unReadNoticesData.pageSize}
                  current={unReadNoticesData.current}
                  onChange={(current, pageSize) => {
                    toRefreshNoticeModule({ current, pageSize })
                  }}
                />
              )}
              {unReadNoticesData.total === 0 && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
            </div>
          }
        >
          <Badge overflowCount={99} count={unReadNoticesData.total || 0} className='mr20px'>
            <BellOutlined style={{ fontSize: 20, cursor: 'pointer' }} className='c-#c0c4cc' />
          </Badge>
        </Popover>
      </div>
    </>
  )
}

export default connect(({ [namespace]: modelState }) => ({ modelState }))(Notice)
